/*
 * $Author: isan.wong@gmail.com $
 * $Date: 2011-07-29 01:03:06 +0000 (Fri, 29 Jul 2011) $
 * $Rev: 13 $
 * $URL: http://capitalbio-smd.googlecode.com/svn/src/com/capitalbio/smd/base/StdGeneFactory.java $
 */

package com.capitalbio.smd.base;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.biojava.bio.BioException;
import org.biojavax.bio.seq.RichSequence;
import org.biojavax.bio.seq.RichSequenceIterator;
import org.biojavax.bio.seq.RichSequence.IOTools;

/**
 * 标准基因库
 * @author Wang Lei
 */
public class StdGeneFactory {
	protected static Log log = LogFactory.getLog(StdGeneFactory.class);

	private static Map<String, StdGene> lib = new HashMap<String, StdGene>();
	private static String[] names;

	static {
		names = Util.getProperties().getProperty("smd.alignment.genes").split(",");
		
		for (String name : names) {
			log.debug("StdGene: " + name);
		}
	}
	
	/**
	 * 根据基因名称获取基因
	 * @param name
	 * @return StdGene
	 */
	public static StdGene getGene(String name) {
		if (!lib.containsKey(name)) {
			
			StdGene stdGene = null;
			
			//sequence & properties
			try {
				File gbFile = new File(Util.getResourceURL("/lib/" + name + ".gb").toURI());
				RichSequence seq = null;
				RichSequenceIterator richSequenceIterator = IOTools.readGenbankDNA(new BufferedReader(new FileReader(gbFile)), null);
				if (richSequenceIterator.hasNext()) {
					seq = richSequenceIterator.nextRichSequence();
				}
				
				File propertiesFile = null;
				URL propertiesFileUrl = Util.getResourceURL("/lib/" + name + ".properties");
				if (propertiesFileUrl != null) {
					propertiesFile = new File(propertiesFileUrl.toURI());
				}
				
				Properties properties = new Properties();
				if (propertiesFile != null) {
					properties.load(new FileInputStream(propertiesFile));
				}
				
				stdGene = new StdGene(seq, properties);
				
			}
			catch (URISyntaxException e) {
				log.error(e);
			}
			catch (FileNotFoundException e) {
				log.error(e);
			}
			catch (IOException e) {
				log.error(e);
			}
			catch (NoSuchElementException e) {
				log.error(e);
			}
			catch (BioException e) {
				log.error(e);
			}
			
			lib.put(name, stdGene);
		}
		
		return lib.get(name);
	}
	
	/**
	 * 列出库中的基因
	 * @throws URISyntaxException 
	 */
	public static String[] getNames() {
		return names;
	}
}
